package com.ygt.tomcat;

import com.ygt.conf.ServletConfigMapping;
import com.ygt.servlet.HttpServlet;
import com.ygt.util.ResponseUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author ygt
 * @Date 2022/11/17 17:37
 * @Version 1.0
 */
public class MyTomcat {

    Request request = new Request();

    //获取类对象生成servlet对象
    public void dispatch(Request request,Response response) throws Exception {
        Class<HttpServlet> servletClass = ServletConfigMapping.classMap.get(request.getUrl());
        if (servletClass != null){
            HttpServlet servlet = servletClass.newInstance();   //生成当前servlet对象
            servlet.service(request,response);
        }
    }

    //启动tomcat的主方法
    public void startUp() throws Exception {
        //加载servlet信息
        ServletConfigMapping.initServlet(); //启动阶段

        //定义ServerSocket8080端口
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true){
            Socket socket = serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        handler(socket);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    //解析用户请求数据
    public void handler(Socket socket) throws Exception {
        InputStream inputStream = socket.getInputStream();
        getInput(inputStream);//解析Http请求

        //获取输出通道、获取输出流
        Response response = new Response(socket.getOutputStream());

        if (request.getUrl().equals("")){
            //返回404
            response.GetWriter(ResponseUtil.getResponseHeader404());
        }else if (ServletConfigMapping.classMap.get(request.getUrl()) == null){
            //访问的是静态资源
            response.GetWriterHtml(request.getUrl());
        }else {
            //访问的是动态资源
            dispatch(request,response);
        }

    }

    //解析Http请求
    public void getInput(InputStream inputStream) throws IOException {
        int count = 0;
        while(count == 0){
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);
        String content = new String(bytes);
        System.out.println(content);

        if(content.equals("")){
            System.out.println("你有一个空请求");
        }else{
            String firstLine = content.split("\\n")[0];
            request.setMethod(firstLine.split("\\s")[0]);
            request.setUrl(firstLine.split("\\s")[1]);
        }
    }


    public static void main(String[] args) throws Exception {
        MyTomcat myTomcat = new MyTomcat();
        myTomcat.startUp();

    }


}
